package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到fasfdfs
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //3.保存素材数据到表中 wm_material

        WmUser user = WmThreadLocalUtils.getUser();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUserId(user.getId());
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl+fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //1.检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.封装条件 分页条件 查询条件
        Page<WmMaterial> pageRequest = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.<WmMaterial>lambdaQuery();

        if (dto.getIsCollected() !=null && dto.getIsCollected().equals(1)){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,1);
        }

        //3.执行查询
        IPage<WmMaterial> pageResult = page(pageRequest, lambdaQueryWrapper);

        List<WmMaterial> list = pageResult.getRecords();


        list=list.stream().map((item)->{               //对每一个元素进行处理
            item.setUrl(fileServerUrl+item.getUrl());  //添加前置路径
            return item;
        }).collect(Collectors.toList());               //将所有处理好的素材收集到一个新的集合中

        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal());

        responseResult.setData(list);

        return responseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {

        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断素材有没有被引用

        Integer count = wmNewsMaterialMapper.selectCount(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getMaterialId, id)
        );

        if (count!=null && count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前素材被引用,不能删除");
        }

        //获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.根据id 和当前登录用户id 查询出素材

        WmMaterial wmMaterial = getOne(Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId())
        );

        //4.根据素材获取文件路径
        fastDFSClient.delFile(wmMaterial.getUrl());

        removeById(id);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {

        //1.检查参数
        if (id==null || (!WemediaContans.CANCEL_COLLECT_MATERIAL.equals(type) && !WemediaContans.COLLECT_MATERIAL.equals(type))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.根据id 和 登录用户id 进行收藏修改

        update(
                Wrappers.<WmMaterial>lambdaUpdate()
                        .set(WmMaterial::getIsCollection,type)
                        .eq(WmMaterial::getId,id)
                        .eq(WmMaterial::getUserId,user.getId())
        );

        return ResponseResult.okResult();
    }
}